package com.example.administrator.basedemos.activity;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.basedemos.R;
import com.example.administrator.basedemos.adapter.MainAdapter;
import com.example.administrator.basedemos.api.GitHubAPi;
import com.example.administrator.basedemos.base.BaseActivity;
import com.example.administrator.basedemos.bean.GithubUserBean;
import com.example.administrator.basedemos.bean.UserBean;
import com.example.administrator.basedemos.utils.LogUtil;
import com.example.administrator.basedemos.utils.TmtUtils;

import java.util.ArrayList;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 创建者     ZCL
 * 创建时间   2018/3/12 17:37
 * 描述	      ${TODO}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */

public class Rxjava2Activity extends BaseActivity {
    private static final String TAG = "Rxjava2Activity";
    @BindView(R.id.recyclerview_weight)
    RecyclerView mRecyclerviewWeight;
    private MainAdapter mAdapter;
    private Observable  mObservable;
    private Observer    mObserver;
    private Consumer    mConsumer;
    private String BaseUrl = "https://api.github.com/";
    private GitHubAPi mAPiService;

    //https://api.github.com/users/1

    @Override
    public void initView() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                //.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        mAPiService = retrofit.create(GitHubAPi.class);

        mObservable = getObserverable();
        mObserver = getObserver();
        mConsumer = getConsumer();
    }

    private Observable getObserverableJust() {
        return Observable.just("hello!", "I'm zhang");
    }

    private Observable getObserverableArray() {
        return Observable.fromArray("sanme?", "same", "yes");
    }

    private Observable getObserverable() {
        Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitter.onNext("hello");
                emitter.onNext("I'm Zhang");
                emitter.onComplete();
                //emitter.onError(exception);
            }
        });
        return observable;
    }

    private Consumer getConsumer() {
        final Consumer onNext = new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {

                TmtUtils.midToast(Rxjava2Activity.this, s);
            }
        };
        return onNext;
    }

    private Observer getObserver() {

        Observer observer = new Observer<String>() {
            public Disposable dd;

            @Override
            public void onSubscribe(Disposable d) {
                dd = d;
            }

            @Override
            public void onNext(String o) {
                if (o.equals("暂停")) {
                    dd.dispose();//解除订阅
                }
                TmtUtils.midToast(Rxjava2Activity.this, o);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                TmtUtils.midToast(Rxjava2Activity.this, "Rx complete!");
            }
        };
        return observer;
    }

    @Override
    public void initData() {
        final ArrayList<String> list = new ArrayList<>();

        list.add("observer");
        list.add("cousum");
        list.add("just");
        list.add("arrylist");
        list.add("ThradPool");
        list.add("SimpleMap");
       // list.add(new MainItem("flatmap"));



        mRecyclerviewWeight.setLayoutManager(new GridLayoutManager(this, 3));
        mAdapter = new MainAdapter(R.layout.main_item, list);
        mAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
            @Override
            public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                int length = list.get(position).length();
                if (list.get(position).length() > 6) {
                    return 3;
                } else {
                    return 2;
                }
            }
        });
        mRecyclerviewWeight.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (position) {
                    case 0:
                        mObservable.subscribe(mObserver);
                        break;
                    case 1:
                        mObservable.subscribe(mConsumer);
                        break;
                    case 2:
                        mObservable = getObserverableJust();
                        mObservable.subscribe(mConsumer);
                        break;
                    case 3:
                        mObservable = getObserverableArray();
                        mObservable.subscribe(mConsumer);
                        break;
                    case 4:
                        testThreadPool();
                        break;
                    case 5:
                        simpleMap();
                        break;
                    case 6:
                        flatMap();
                        break;
                    case 7:
                        flatMap();
                        break;
                }
            }
        });
    }

    private void flatMap() {
        Observable.just(getParams()).flatMap(new Function<UserBean, ObservableSource<GithubUserBean>>() {
            @Override
            public ObservableSource<GithubUserBean> apply(UserBean userBean) throws Exception {
               ///通过上传parmabean得到GitHubBean 并在此返回一个可发射的observaerable 将GithubUserBean发送出去
                //GithubUserBean githubUserBean = mAPiService.login(userBean).execute().body(); -->retrofit 方式
                //将github作为下次请求参数发送出去
                //return Observable.just(githubUserBean);
               //rx+retrofit 方式
                return mAPiService.rxLogin(userBean);

            }

        }).flatMap(new Function<GithubUserBean, ObservableSource<UserBean>>() {
            @Override
            public ObservableSource<UserBean> apply(GithubUserBean githubUserBean) throws Exception {
                //假设通过token获取更多个人信息
               // UserBean userBean = mAPiService.Token(githubUserBean.getName()).execute().body();
                //return Observable.just(userBean);  -->retrofit 方式

                //rx+retrofit 方式
                return mAPiService.rxToken(githubUserBean.token);
            }
        }).subscribeOn(Schedulers.io())//无上限线程池 重复使用
        .observeOn(AndroidSchedulers.mainThread())//更新界面切换回主线程
        .subscribe(new Consumer<UserBean>() {
            @Override
            public void accept(UserBean userBean) throws Exception {
                TmtUtils.midToast(Rxjava2Activity.this,"更新UI!");
            }
        });
    }

    /**
     * UserBean 账号密码封装进去一次来登陆
     */
    private UserBean getParams() {
        return new UserBean("zhang","zcl");
    }

    private void simpleMap() {
            Observable.create(new ObservableOnSubscribe<Integer>() {
                @Override
                public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                    emitter.onNext(1);
                    emitter.onNext(2);
                    emitter.onNext(3);
                }
            }).map(new Function<Integer, String>() {
                @Override
                public String apply(Integer integer) throws Exception {
                    return "map："+integer;
                }
            }).subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) throws Exception {
                    LogUtil.util(TAG,"map返回数据是:"+s);
                }
            });
    }

    private void testThreadPool() {
        Observable.create(new ObservableOnSubscribe<GithubUserBean>() {
            @Override
            public void subscribe(ObservableEmitter<GithubUserBean> emitter) throws Exception {
                /**
                 * 此县城是主线程 所以请求网络必须设置Schedulers.io()强请求放入子线程
                 * 级的一定是body否则返回的是call不是GithubUserBean
                 */
                GithubUserBean body = mAPiService.githubUserOne("1").execute().body();
                emitter.onNext(body);
            }
        }).subscribeOn(Schedulers.io())
                /**
                 * 前面设置为子线程所以更新ui时候必须切换到主线程
                 */
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GithubUserBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(GithubUserBean githubUserBean) {
                        /**
                         这里是用来显示UI界面所以我们要设置成主线程 AndroidSchedulers.mainThread()
                         */
                        LogUtil.util(TAG, "返回数据是:" + githubUserBean.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_rxjava;
    }

}
